package com.sjy.mvvmdemo.main

import android.content.Intent
import android.util.Log
import androidx.core.content.ContextCompat.startActivity
import androidx.databinding.Bindable
import androidx.databinding.Observable
import androidx.databinding.PropertyChangeRegistry
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.sjy.mvvmdemo.SecondActivity

/**
 * MainActivity的绑定ViewModel 和xml的交互都由该vm处理
 * 使用ViewModel进行数据绑定的实现方式：实现Observable接口+@Bindable注解，如果act中加监听，添加LiveData<>即可
 * 推荐使用LiveData
 */
class MainViewModel : ViewModel(), Observable {
    //==============================错误信息-liveData方法==============================
    //错误信息
    private val statusMessage = MutableLiveData<String>()

    //将信息返回给act处理信息
    val msg: LiveData<String>
        get() = statusMessage

    //==============================信息监听-liveData方法==============================
    //将信息返回给act处理信息
    val nameMsg: LiveData<String>
        get() = inputName

    //数据更新
    var lists = MutableLiveData<ArrayList<Person>>()

    //用于监听变化,在act中监听
    val listDatas: LiveData<ArrayList<Person>>
        get() = lists

    //==============================（1）Observable数据绑定方式==============================
    // @Bindable+MutableLiveData<String>(),在xml中绑定该属性： android:text="@={mMainViewModel.mName}"，即可双向绑定
    @Bindable
    val inputName = MutableLiveData<String>()

    @Bindable
    val inputAge = MutableLiveData<String>()


    //保存按钮监听
    fun saveOrUpdate() {
        if (inputName.value.isNullOrEmpty()) {
            Log.d("SJY", "请输入姓名")
            statusMessage.value = "请输入姓名"
        } else if (inputAge.value.isNullOrEmpty()) {
            Log.d("SJY", "请输入年龄")
            statusMessage.value = "请输入年龄"
        } else {
            updateList(inputName.value!!.toString(), inputAge.value!!.toInt())
        }
    }

    fun deleteAll() {
        list.clear()
        this.lists.postValue(list)//发送监听事件
    }



    var list = ArrayList<Person>()
    private fun updateList(name: String = "", age: Int = 0) {
        //更新数据
        list.add(Person(name, age))
        this.lists.postValue(list)//发送监听事件

        //清空显示
        inputName.value = null
        inputAge.value = null
    }

    //==============================Observable的两个复写方法：Observable实现数据的绑定==============================

    //https://blog.csdn.net/qq_29983773/article/details/100656485
    private val callbacks: PropertyChangeRegistry by lazy { PropertyChangeRegistry() }
    override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

        Log.d("SJY", "removeOnPropertyChangedCallback")
//        callbacks.add(callback)
    }

    override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
        Log.d("SJY", "addOnPropertyChangedCallback")
//        callbacks.remove(callback)
    }

}